/*
 * Copyright 2012 Marsrutai.lt
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package lt.marsrutai.mobile.android.activity;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;

import lt.marsrutai.mobile.android.AppContext;
import lt.marsrutai.mobile.android.R;
import lt.marsrutai.mobile.android.activity.intent.SchedulesIntentHolder;
import lt.marsrutai.mobile.android.activity.intent.StopSearchIntentHolder;
import lt.marsrutai.mobile.android.activity.intent.TaskIntentHolder;
import lt.marsrutai.mobile.android.adapter.TabAdapter;
import lt.marsrutai.mobile.android.adapter.TabInfoProvider;
import lt.marsrutai.mobile.android.cache.UpdateCacheRequest;
import lt.marsrutai.mobile.android.fragment.SchedulesFragment;
import lt.marsrutai.mobile.android.fragment.task.GetSchedulesTaskFragment;
import lt.marsrutai.mobile.android.fragment.task.TaskFragment;
import lt.marsrutai.mobile.android.handler.menu.MenuHandler;
import lt.marsrutai.mobile.android.handler.menu.SchedulesMenuHandler;
import lt.marsrutai.mobile.android.manager.ActivityManager;
import lt.marsrutai.mobile.android.model.Schedule;
import lt.marsrutai.mobile.android.service.TransportInfoResolver.TransportInfo;
import lt.marsrutai.mobile.android.task.GetSchedulesTask;
import lt.marsrutai.mobile.android.task.GetTracksTask;
import lt.marsrutai.mobile.android.util.PreferenceUtils;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.view.ViewPager;

import com.viewpagerindicator.TabPageIndicator;

public class SchedulesActivity extends BaseActivity {
    
    private static final String GET_SCHEDULES_TASK_FRAGMENT_TAG = "getSchedulesStops";
    
    private FragmentManager fragmentManager;
    private ActivityManager manager;
    
    private ViewPager viewPager;

    private List<Schedule> schedules;
    private String scopeFolder;
    
    /** Temp. variable. Used for saving currently active tab index */ 
    private int tabIndex = 0;

    private BroadcastReceiver schedulesReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            TaskIntentHolder holder = new TaskIntentHolder(intent);

            switch (holder.getStatus()) {
                case Activity.RESULT_OK:
                    schedules = holder.getListResult();
                    initialize();
                    manager.dismissDownloadLoadingBar();
                    break;
                case GetTracksTask.RESULT_NOT_RESOLVED:
                    manager.runOnUiThread(manager.errorRes);
                    break;
                default:
                    manager.dismissDownloadLoadingBar();
            }
        }
    };
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        fragmentManager = getSupportFragmentManager();
        manager = new ActivityManager(this);

        // Display loading in the temp view while the data is downloading
        setContentView(R.layout.progress_spinner);
        manager.showDownloadLoadingBar();

        restoreState(savedInstanceState);

        showDownloadAdvice();
    }

    @Override
    protected void onResume() {
        super.onResume();
        LocalBroadcastManager.getInstance(this).registerReceiver(schedulesReceiver, new IntentFilter(GetSchedulesTask.BROADCAST_ACTION));

        if (schedules == null) {
            // Check whether the worker fragment has been retained
            TaskFragment<?, ?, ?> taskFragment = (TaskFragment<?, ?, ?>) fragmentManager.findFragmentByTag(GET_SCHEDULES_TASK_FRAGMENT_TAG);
    
            // Start downloading only if we don't have any scopes, and task fragments has not been retained
            if (!TaskFragment.isActive(taskFragment)) {
                downloadData();
            }
        }
        else {
            // already have all the data - display it
            initialize();
            manager.dismissDownloadLoadingBar();
        }
    }

    @Override
    public void onPause() {
        super.onPause();

        LocalBroadcastManager.getInstance(this).unregisterReceiver(schedulesReceiver);
        
        if (viewPager != null) {
            tabIndex = viewPager.getCurrentItem();
        }
    }

    private void restoreState(Bundle bundle) {
        if (bundle == null) {
            bundle = getIntent().getExtras();
        }
        
        SchedulesIntentHolder intentHolder = new SchedulesIntentHolder(bundle);
        
        tabIndex = intentHolder.getTabIndex();
        scopeFolder = intentHolder.getScopeFolder();
        schedules = intentHolder.getSchedules();
    }
    
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        SchedulesIntentHolder intentHolder = new SchedulesIntentHolder(new Bundle());
        
        intentHolder.setTabIndex(viewPager == null ? 0 : viewPager.getCurrentItem());
        intentHolder.setSchedules(schedules);
        intentHolder.setScopeFolder(scopeFolder);
        
        outState.putAll(intentHolder.getIntent().getExtras());
        
        super.onSaveInstanceState(outState);
    }

    /**
     * Creates tabs for each schedule group and initializes the adapter
     */
    private void initialize() {
        TabAdapter adapter = new TabAdapter(getSupportFragmentManager());

        for (Entry<TransportInfo, List<Schedule>> entry : getGroupedSchedules().entrySet()) {
            // Fill intent holder with proper info
            SchedulesIntentHolder intentHolder = new SchedulesIntentHolder(getIntent().getExtras());
            intentHolder.setSchedules(entry.getValue());
            
            // Add tab
            adapter.addTab(new TabInfoProvider(SchedulesFragment.class, 
                    intentHolder.getIntent().getExtras(), 
                    entry.getKey().getLocalizedNamePlural()));
        }

        // Attach the adapted to the view pager
        setContentView(R.layout.tabs_viewpager_layout);
        viewPager = (ViewPager) findViewById(R.id.viewpager);
        viewPager.setAdapter(adapter);
        // Attach view pager to tab page indicator
        TabPageIndicator indicator = (TabPageIndicator) findViewById(R.id.indicator);
        indicator.setViewPager(viewPager);
        
        if (tabIndex >= 0) {
            viewPager.setCurrentItem(tabIndex);
        }
    }

    private void downloadData() {
        SchedulesIntentHolder schedulesIntentHolder = new SchedulesIntentHolder(getIntent().getExtras());
        String scopeFolder = schedulesIntentHolder.getScopeFolder();
        
        TaskFragment.download(fragmentManager, 
                GetSchedulesTaskFragment.class, GET_SCHEDULES_TASK_FRAGMENT_TAG,
                new String[] { scopeFolder });
    }
    
    protected Map<TransportInfo, List<Schedule>> getGroupedSchedules() {
        Map<TransportInfo, List<Schedule>> groupedSchedules = new TreeMap<TransportInfo, List<Schedule>>(TransportInfo.INDEX_COMPARATOR);

        for (Schedule schedule : schedules) {
            TransportInfo transportInfo = AppContext.getTransportInfoResolver().getTransportInfo(scopeFolder, schedule.getTransportId());
            if (!groupedSchedules.containsKey(transportInfo)) {
                groupedSchedules.put(transportInfo, new ArrayList<Schedule>());
            }
            groupedSchedules.get(transportInfo).add(schedule);
        }
        
        return groupedSchedules;
    }

    private void showDownloadAdvice() {
        if (Boolean.FALSE.equals(PreferenceUtils.getPreferenceValue(this, PreferenceUtils.SCHEDULE_ACTIVITY_OPENED))) {
            PreferenceUtils.setBooleanPreferenceValue(this, PreferenceUtils.SCHEDULE_ACTIVITY_OPENED, Boolean.TRUE);

            SchedulesIntentHolder sourceIntentHolder = new SchedulesIntentHolder(getIntent());
            AppContext.getCacheUpdateManager().showDownloadScopeAdviceDialog(
                    this,
                    new UpdateCacheRequest(sourceIntentHolder.getScopeFolder(), sourceIntentHolder.getScopeName(),
                            UpdateCacheRequest.Section.SCHEDULES));
        }
    }

    @Override
    public int getMenuResource() {
        return R.menu.schedules_menu;
    }

    @Override
    public MenuHandler getMenuHandler() {
        return new SchedulesMenuHandler();
    }

    @Override
    public boolean onNavigationItemSelected(int itemPosition, long itemId) {
        if (itemPosition == 1) {
            startActivity(new Intent(this, ScopesActivity.class));
        }
        return false;
    }

    @Override
    public NavMenuData getNavMenuData() {
        SchedulesIntentHolder schedulesIntentHolder = new SchedulesIntentHolder(getIntent());
        return new NavMenuData(new String[] { schedulesIntentHolder.getScopeName(), getString(R.string.home) });
    }

    @Override
    public boolean onSearchRequested() {
        SchedulesIntentHolder sourceIntentHolder = new SchedulesIntentHolder(getIntent());

        StopSearchIntentHolder stopSearchIntentHolder = new StopSearchIntentHolder(new Bundle());
        stopSearchIntentHolder.setScopeFolder(sourceIntentHolder.getScopeFolder());
        stopSearchIntentHolder.setScopeName(sourceIntentHolder.getScopeName());

        startSearch(null, false, stopSearchIntentHolder.getIntent().getExtras(), false);

        return true;
    };
}
